package com.cn.qtms.controller;


import com.cn.qtms.common.controller.BaseRestController;
import com.cn.qtms.common.result.Result;
import com.cn.qtms.common.result.ResultUtil;
import com.cn.qtms.util.poi.ExcelUtils;
import com.cn.qtms.entity.vo.CouponNoVo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Name:ExcelController
 * @Description:Excel导入导出
 * @Author: Neil
 * @Date: 2019-08-09 15:59
 **/
@RestController
@RequestMapping("/excel")
public class ExcelController extends BaseRestController {

//    @Autowired
//    private CmsService cmsService;

    @RequestMapping(value = "/export/coupon/{id}", method = RequestMethod.GET)
    public void exportCoupon(@PathVariable("id")Long id , HttpServletResponse response) throws IOException {

//        List<String[]> resultList = cmsService.getCouponNoList(id);  //cmsService.getCouponNoList(map);
        List<String[]> resultList=new ArrayList<>();
        List<CouponNoVo> dataList = new ArrayList<>();
        resultList.forEach(
               obj -> dataList.add(new CouponNoVo(obj[0],obj[1]))
        );
        long t1 = System.currentTimeMillis();
        ExcelUtils.writeExcel(response, dataList, CouponNoVo.class,"coupon.xlsx");
        long t2 = System.currentTimeMillis();
        System.out.println(String.format("write over! cost:%sms", (t2 - t1)));
    }

    @RequestMapping(value = "/import/coupon", method = RequestMethod.POST)
    public Result<List<CouponNoVo>> importCoupon(@RequestParam(value = "file") MultipartFile file) {

        long t1 = System.currentTimeMillis();
        List<CouponNoVo> list = ExcelUtils.readExcel("", CouponNoVo.class, file);
        long t2 = System.currentTimeMillis();
        System.out.println(String.format("read over! cost:%sms", (t2 - t1)));

        List<CouponNoVo> couponNoList = new ArrayList<>();
        list.forEach(
                b -> {
                        couponNoList.add(new CouponNoVo(b.getCouponNo(), b.getCouponSecret()));
                }
        );
        //去重
        List<CouponNoVo> distinctList = couponNoList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
                new TreeSet<>(Comparator.comparing(CouponNoVo::getCouponNo))), ArrayList::new));

        //分布式事务-调用其他模块进行导入
        return ResultUtil.success(distinctList);
    }


}
